package com.clgk.wechatmall.common.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.NamedThreadLocal;


public class SysLogInterceptor extends BaseHandlerInterceptorAdapter
{
    private static Logger logger = Logger.getLogger(SysLogInterceptor.class);

    private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>(
            "StopWatch-StartTime");

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception
    {
        long beginTime = System.currentTimeMillis();
        startTimeThreadLocal.set(beginTime);
        String path = request.getServletPath();
        if (StringUtils.isBlank(path))
        {
            path = request.getRequestURI();
        }
        logger.info("Start: " + path);
        return true;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception
    {
        long endTime = System.currentTimeMillis();
        long beginTime = startTimeThreadLocal.get();
        long consumeTime = endTime - beginTime;

        String path = request.getServletPath();
        if (StringUtils.isBlank(path))
        {
            path = request.getRequestURI();
        }
        logger.info("End: " + path + ". Time: " + consumeTime + "ms.");
        Map params = request.getParameterMap();
        ObjectMapper objectMapper = new ObjectMapper();
        logger.info("Params:" + objectMapper.writeValueAsString(params));

        if (consumeTime > 3000)
            logger.info(String.format("%s consume %d millis", path, consumeTime));
        }
}
